package com.jader.fragment;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ExpandableListView;
import android.widget.ExpandableListView.OnChildClickListener;
import android.widget.ExpandableListView.OnGroupClickListener;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.jader.activities.OrderDetailActivity;
import com.jader.activities.Store;
import com.jader.adapter.OrderAdapter;
import com.jader.beans.OrderDetail;
import com.jader.util.JaderApplication;
import com.jader.util.PreferenceUtil;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;
import com.zlp.jader.R;

public class AllOrderFragment extends Fragment {
	ExpandableListView orderListView;
	View AllOrder;
	private HttpUtils httpUtils;
	OrderAdapter orderAdapter;

	List<String> sellerName = new ArrayList<String>();
	List<OrderDetail> orderList = new ArrayList<OrderDetail>();
	Map<String, List<OrderDetail>> orderMap = new HashMap<String, List<OrderDetail>>();

	@Override
	public void onAttach(Activity activity) {
		// TODO Auto-generated method stub
		super.onAttach(activity);
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
	}

	@Override
	public void onResume() {
		// TODO Auto-generated method stub
		super.onResume();

	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		AllOrder = inflater.inflate(R.layout.fragment_allorder, null);
		initViews();
		clickEvent();
		sendRequest();
		return AllOrder;
	}

	/** 初始化视图 */
	private void initViews() {
		orderListView = (ExpandableListView) AllOrder
				.findViewById(R.id.listview_order);
		orderAdapter = new OrderAdapter(sellerName, orderMap, getActivity());
		orderListView.setAdapter(orderAdapter);
		orderListView.setGroupIndicator(null);
	}

	private void clickEvent() {
		// 点击Group不收缩
		orderListView.setOnGroupClickListener(new OnGroupClickListener() {
			@Override
			public boolean onGroupClick(ExpandableListView parent, View v,
					int groupPosition, long id) {
				String sellername = (String) orderAdapter
						.getGroup(groupPosition);
				int sellerid = orderMap.get(sellername).get(groupPosition)
						.getSeller().getSellerid();
				Intent seller = new Intent(getActivity(), Store.class);
				seller.putExtra("sellerid", sellerid);
				startActivity(seller);
				return true;
			}
		});

		orderListView.setOnChildClickListener(new OnChildClickListener() {

			@Override
			public boolean onChildClick(ExpandableListView parent, View v,
					int groupPosition, int childPosition, long id) {
				OrderDetail order = (OrderDetail) orderAdapter.getChild(
						groupPosition, childPosition);
				Intent detail = new Intent(getActivity(),
						OrderDetailActivity.class);
				detail.putExtra("order", order);
				startActivity(detail);
				return false;
			}
		});
	}

	/** 发送请求 */
	private void sendRequest() {
		String url = JaderApplication.getIP() + "/Jader/client";
		RequestParams params = new RequestParams();
		params.addBodyParameter("type", "" + JaderApplication.ORDER_SELECT);
		params.addBodyParameter("userid",
				PreferenceUtil.getInstance(getActivity()).getShareUserId());
		httpUtils = new HttpUtils();
		httpUtils.send(HttpMethod.POST, url, params,
				new RequestCallBack<String>() {

					@Override
					public void onFailure(HttpException arg0, String arg1) {
						JaderApplication.show(getActivity(), "连接异常");

					}

					@Override
					public void onSuccess(ResponseInfo<String> info) {
						String order = info.result;
						Gson gson = new Gson();
						Type typeofType = new TypeToken<List<OrderDetail>>() {
						}.getType();
						List<OrderDetail> list = gson.fromJson(order,
								typeofType);
						orderList.clear();
						orderMap.clear();
						sellerName.clear();
						for (OrderDetail orderDetail : list) {
							boolean flag = true;
							for (OrderDetail orderDetail2 : orderList) {
								if (orderDetail.equals(orderDetail2)) {
									flag = false;
								}
							}
							if (flag) {
								orderList.add(orderDetail);
								for (int i = 0; i < orderList.size(); i++) {
									orderMap.put(orderList.get(i).getSeller()
											.getSellername(), null);
								}
								Set<Entry<String, List<OrderDetail>>> set = orderMap
										.entrySet();
								Iterator<Entry<String, List<OrderDetail>>> iterator = set
										.iterator();

								while (iterator.hasNext()) {
									Entry<String, List<OrderDetail>> entry = iterator
											.next();
									boolean nameflag = true;
									for (String name : sellerName) {
										if (entry.getKey().equals(name)) {
											nameflag = false;
										}
									}
									if (nameflag) {
										sellerName.add(entry.getKey());
									}
								}
								for (int i = 0; i < sellerName.size(); i++) {
									List<OrderDetail> goodsList = new ArrayList<OrderDetail>();
									for (int j = 0; j < orderList.size(); j++) {
										if (sellerName.get(i).equals(
												orderList.get(j).getSeller()
														.getSellername())) {
											goodsList.add(orderList.get(j));
										}
									}
									orderMap.put(sellerName.get(i), goodsList);
								}
							}
							orderAdapter.notifyDataSetChanged();
						}

						// 展开列表
						for (int i = 0; sellerName != null
								&& i < sellerName.size(); i++) {
							orderListView.expandGroup(i);
						}
					}
				});
	}
}
